package com.planesnet.task1;

import helper.MySQLiteHelper;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class CopyOfTaskDataSource {

	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
			MySQLiteHelper.COLUMN_NAME };

	public CopyOfTaskDataSource(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public Task create(String comment) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_NAME, comment);
		long insertId = database.insert(MySQLiteHelper.TABLE_TASKS, null,
				values);
		// To show how to query
		Cursor cursor = database.query(MySQLiteHelper.TABLE_TASKS,
				allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		return cursorToTask(cursor);
	}

	public void delete(Task comment) {
		long id = comment.getId();
		System.out.println("Task deleted with id: " + id);
		database.delete(MySQLiteHelper.TABLE_TASKS, MySQLiteHelper.COLUMN_ID
				+ " = " + id, null);
	}

	public List<Task> getAll() {
		List<Task> tasks = new ArrayList<Task>();
		Cursor cursor = database.query(MySQLiteHelper.TABLE_TASKS,
				allColumns, null, null, null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Task task = cursorToTask(cursor);
			tasks.add(task);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return tasks;
	}

	private Task cursorToTask(Cursor cursor) {
		Task task = new Task();
		task.setId(cursor.getLong(0));
		task.setName(cursor.getString(1));
		return task;
	}
}
